package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 查询列表
     *
     * @param dto
     * @return
     */

    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1 参数检查
        dto.checkParam();
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2 条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> realnameIPage = page(page, wrapper);
        // 3 返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), realnameIPage.getTotal(), realnameIPage.getRecords());
        return pageResponseResult;
    }

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.校验参数
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "实名认证信息不能为空");
        }
        //  根据市民认证的id 查询实名认证信息
        ApUserRealname apUserRealname = getById(dto.getId());
        if (apUserRealname == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证信息不存在");
        }
        // 判断实名认证的状态是否为待审核 （1 2 9）
        if (!AdminConstants.WAIT_AUTH.equals(dto.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "实名认证不是待审核状态");
        }
        // 根据实名认证关联的userId查询出apuser对象信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "未发现该实名认证关联的apuser信息");
        }
        //2.修改实名认证的状态
        apUserRealname.setStatus(status);
        apUserRealname.setReason(dto.getMsg());
        this.updateById(apUserRealname);
        //3.如果状态为9
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //3.1 开通自媒体账户
            WmUser wmUser = creatWmuser(apUser);
            //3.2创建作者信息
            creatAuthor(wmUser,apUser);

        }
        return ResponseResult.okResult();
    }

    /**
     * 远程创建作者信息
     * @param wmUser
     * @param apUser
     */
    @Autowired
    private ArticleFeign articleFeign;
    private void creatAuthor(WmUser wmUser, ApUser apUser) {
        //1.先根据apuserId远程查询作者信息
        ResponseResult<ApAuthor> authorResult = articleFeign.findByUserId(apUser.getId());
        if (authorResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //2.判断作者信息是否存在
        ApAuthor author = authorResult.getData();
        if (author!=null){
            //3.如果存在，提示作者已存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已经存在，请不要重复创建");
        }
        //4.如果不存在，创建作者信息
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(apUser.getId());
        //5.远程保存作者信息
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.save(apAuthor);
        if (apAuthorResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }


    /**
     * 远程开通自媒体用户
     *
     * @param apUser
     * @return
     */
    @Autowired
    private WemediaFeign wemediaFeign;

    private WmUser creatWmuser(ApUser apUser) {
        //1.根据用户名 远程查询自媒体账户
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        //2.如果有该用户 抛出异常 自媒体用户已经存在
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        if (wmUser!=null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"自媒体用户已存在，开通失败");
        }
        //3.如果没有该用户 创建新的自媒体用户
         wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(0);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        //4.远程保存自媒体用户
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (!saveResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        return saveResult.getData();
    }
}
